<template>
  <div class="app-container">
    <!-- 步骤条 -->
    <el-steps :active="feeStep" finish-status="success" align-center>
      <el-step title="确定电表误差" />
      <el-step v-if="feeDialogRow.dflx == 2 || feeDialogRow.dflx == 4" title="生成容量系数" />
      <el-step v-if="feeDialogRow.dflx == 3 || feeDialogRow.dflx == 4" title="生成服务费" />
      <el-step title="确认电表电费" />
      <el-step title="确认客户电费" />
    </el-steps>
    <div style="margin: 32px 0">
      <!-- 步骤1：电表误差列表 -->
      <template v-if="feeStep === 0">
        <el-tabs v-model="meterTab" @tab-click="handleMeterTabChange">
          <el-tab-pane label="使用中" name="using"></el-tab-pane>
          <el-tab-pane label="本月启用" name="start"></el-tab-pane>
          <el-tab-pane label="本月退用" name="stop"></el-tab-pane>
        </el-tabs>
        <el-table :data="meterList" v-loading="meterLoading"  size="small" style="margin: 24px 0">
          <el-table-column prop="dbzyid" label="序号" align="center" width="60" />
          <el-table-column prop="dbbh" label="电表编号" align="center" />
          <el-table-column prop="zt" label="载体" align="center" />
          <el-table-column prop="fjh" label="房间号" align="center" />
          <el-table-column prop="qymc" label="租户名称" align="center"  width="280" show-overflow-tooltip />
          <el-table-column prop="jfsjtime" label="电表启用时间" align="center" />
          <el-table-column label="计费状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.yx === 1" type="success">计费中</el-tag>
              <el-tag v-else type="danger">未计费</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-button v-if="scope.row.yx === 1" size="mini" type="danger" @click="toggleMeterStatus(scope.row)">取消计费</el-button>
              <el-button v-else size="mini" type="primary" @click="toggleMeterStatus(scope.row)">纳入计费</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="meterPage.total > 0"
          :total="meterPage.total"
          v-model:page="meterPage.pageNum"
          v-model:limit="meterPage.pageSize"
          @pagination="loadMeterList"
        />
      </template>
      <!-- 步骤2：生成容量系数 -->
      <template v-if="(feeDialogRow.dflx == 2 && feeStep === 1) || (feeDialogRow.dflx == 4 && feeStep === 1)">
        <div>
          <el-button type="primary" icon="Plus" @click="openCheckDialog" style="margin-bottom: 10px">新增容量电量</el-button>
          <el-table :data="checkList"  style="margin-bottom: 10px">
            <el-table-column prop="zt" label="载体" align="center" />
            <el-table-column prop="nf" label="年份" align="center" />
            <el-table-column prop="yf" label="月份" align="center" />
            <el-table-column prop="checkValue" label="容量电量" align="center" />
            <el-table-column prop="ztValue" label="载体电量" align="center" />
            <el-table-column prop="ratio" label="系数" align="center" />
          </el-table>
          <pagination
            v-show="checkTotal > 0"
            :total="checkTotal"
            v-model:page="checkQuery.pageNum"
            v-model:limit="checkQuery.pageSize"
            @pagination="getCheckList"
          />
        </div>
      </template>
      
      <!-- 确认电表电费 -->
      <!-- 步骤4：确认电表电费 -->
      <template v-if="showMeterFeeStep">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
          <span>
            {{ meterFeeConfirmed ? '已确认电表电费数据' : '待确认电表电费数据' }}
          </span>
         
           <span></span>
        </div>
        <el-table :data="meterFeeList"  style="margin-bottom: 10px" v-loading="meterFeeLoading">
         
          <el-table-column prop="dbbh" label="电表编号" align="center" />
          <el-table-column prop="zt" label="载体" align="center" />
          <el-table-column prop="fjh" label="房号" align="center" />
          <el-table-column prop="qymc" label="租户名称" align="center" width="280" show-overflow-tooltip />
          <el-table-column prop="dba" label="期初读数" align="center" />
          <el-table-column prop="dbb" label="期末读数" align="center" />
          <el-table-column prop="dbs" label="电表电量" align="center" />
          <el-table-column prop="dbbl" label="倍率" align="center" />
          <el-table-column prop="dbjs" label="电表计费量" align="center" />
          <el-table-column prop="dfdj" label="电表单价" align="center" />
          <el-table-column prop="dbdf" label="月度电费" align="center" />
          <el-table-column v-if="feeDialogRow.dflx == 2" prop="ratio" label="容量系数" align="center" />
          <el-table-column v-if="feeDialogRow.dflx == 2" prop="checkdf" label="容量电费" align="center" />
        </el-table>
        <pagination
          v-show="meterFeePage.total > 0"
          :total="meterFeePage.total"
          v-model:page="meterFeePage.pageNum"
          v-model:limit="meterFeePage.pageSize"
          @pagination="getMeterFeeList"
        />
      </template>
      <!-- 步骤5：确认客户电费 -->
      <template v-if="feeStep === feeMaxStep"> 
        <el-table :data="zhFeeList"  style="margin-bottom: 10px" v-loading="zhFeeLoading">
          <el-table-column prop="zt" label="载体" align="center" />
          <el-table-column prop="qymc" label="租户名称" align="center"  width="280" show-overflow-tooltip />
          <el-table-column prop="dbyt" label="状态" align="center" />
          <el-table-column prop="nf" label="年份" align="center" />
          <el-table-column prop="yf" label="月份" align="center" />
          <el-table-column prop="hklx" label="费用类型" align="center" />
          <el-table-column prop="zdf" label="应收电费" align="center" />
          <el-table-column prop="zdf" label="合计电费" align="center" />
        </el-table>
        <pagination
          v-show="zhFeePage.total > 0"
          :total="zhFeePage.total"
          v-model:page="zhFeePage.pageNum"
          v-model:limit="zhFeePage.pageSize"
          @pagination="getZhFeeList"
        />
      </template>
    </div>
    <div style="text-align: right">
      <el-button v-if="feeStep > 0" @click="feePrevStep">上一步</el-button>
      <el-button type="primary" @click="feeNextStep">
        <template v-if="showMeterFeeStep&&!meterFeeConfirmed">
      确认{{ getLastMonthStr() }}电表电费
    </template>
    <template v-else-if="feeStep === feeMaxStep">
      确认{{ getLastMonthStr() }}客户应收电费，并生成账单
    </template>
    <template v-else>
      下一步
    </template>
      </el-button>
    </div>

    <!-- 新增容量电量弹窗 -->
    <el-dialog title="新增容量电量" v-model="checkDialogVisible" width="700px" append-to-body>
      <el-form :model="checkForm" :rules="checkRules" ref="checkFormRef" label-width="100px">
        <el-form-item label="载体" prop="zt">
          <el-select v-model="checkForm.zt" placeholder="请选择载体" filterable style="width: 600px" @change="fetchZtValue">
            <el-option v-for="item in carrierList" :key="item.nr" :label="item.nr" :value="item.nr" />
          </el-select>
        </el-form-item>
        <el-form-item label="年月" prop="month">
          <el-date-picker v-model="checkForm.month" type="month" value-format="YYYY-MM" placeholder="请选择年月" style="width: 600px" @change="fetchZtValue" />
        </el-form-item>
        <el-form-item label="载体电量" prop="ztValue">
          <el-input v-model="checkForm.ztValue" disabled placeholder="请先选择载体和年月" />
        </el-form-item>
        <el-form-item label="容量电量" prop="checkValue">
          <el-input v-model="checkForm.checkValue" type="number" @input="calcCheckRatio" placeholder="请输入本月容量电量" />
        </el-form-item>
        <el-form-item label="系数" prop="ratio" placeholder="容量电量/载体电量">
          <el-input v-model="checkForm.ratio" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="checkDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCheckForm">确定</el-button>
      </template>
    </el-dialog>

     
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRouter,useRoute } from "vue-router";

import { parseTime } from "@/utils/ruoyi.js";
const { proxy } = getCurrentInstance();

import {
  selectzt,
  ammeterZyStatus,
  selectMeterList,
  selectMeterFeeList,
  selectZhFeeList,
  confirmMeterFee,
  confirmZhFee,
} from "@/api/carrier/ammeter";
import {
  getCarrierEnergy,
  getCheckEnergyList,
  addCheckEnergy, 
} from "@/api/energy/check";

const route = useRoute();
const router = useRouter();

const feeDialogRow = reactive({
  nr: route.query.zt,
  dflx: 1,
  ...route.query,
});
const feeStep = ref(0);

// 步骤最大值动态计算
const feeMaxStep = computed(() => {
  if (feeDialogRow.dflx == 1) return 2;
  if (feeDialogRow.dflx == 2) return 3;
  if (feeDialogRow.dflx == 3) return 3;
  if (feeDialogRow.dflx == 4) return 4;
  return 2;
});
const showMeterFeeStep = computed(() =>
  (feeDialogRow.dflx == 1 && feeStep.value === 1) ||
  (feeDialogRow.dflx == 2 && feeStep.value === 2) ||
  (feeDialogRow.dflx == 3 && feeStep.value === 2) ||
  (feeDialogRow.dflx == 4 && feeStep.value === 3)
);
// 工具函数
function getLastMonthStr() {
  const d = new Date();
  d.setDate(1); // 设置为当月第一天
  d.setMonth(d.getMonth() - 1);

  console.log(parseTime(d, "{y}-{m}"),parseTime(d),d.getMonth());
  return parseTime(d, "{y}-{m}");
}
// 电表误差相关
const meterList = ref([]);
const meterLoading = ref(false);
const meterPage = reactive({ pageNum: 1, pageSize: 10, total: 0 });
const meterDate = ref(getLastMonthStr());
const meterTab = ref("using");
function handleMeterTabChange(tab,event) {
  meterPage.pageNum = 1;
  meterTab.value = tab.props.name;
  console.log("切换电表误差列表tab:", tab,event);
  loadMeterList();
}
function loadMeterList() {
  meterLoading.value = true;
  let yxa = meterTab.value === "using" ? 1 : meterTab.value === "start" ? 2 : 3;
  selectMeterList({
    date: meterDate.value,
    pageNum: meterPage.pageNum,
    pageSize: meterPage.pageSize,
    yxa,
    zt: feeDialogRow.nr,
  })
    .then((res) => {
      meterList.value = (res.data?.list || []).map((item) => ({
        ...item,
        jfsjtime: parseTime(item.jfsj, "{y}-{m}-{d}"),
      }));
      meterPage.total = res.data?.total || 0;
      meterLoading.value = false;
    })
    .catch(() => {
      meterList.value = [];
      meterPage.total = 0;
      meterLoading.value = false;
    });
}
function toggleMeterStatus(item) {
  const newStatus = item.yx === 1 ? 0 : 1;
  ammeterZyStatus({
    dbzyid: item.dbzyid,
    yx: newStatus,
    zt: feeDialogRow.nr,
  }).then((res) => {
    if (res.code === 200) item.yx = newStatus;
  });
}

// 容量电量相关
const checkQuery = reactive({ year: new Date().getFullYear(), zt: "", pageNum: 1, pageSize: 10 });
const checkList = ref([]);
const checkTotal = ref(0);
function getCheckList() {
  getCheckEnergyList({ ...checkQuery, zt: feeDialogRow.nr }).then((res) => {
    checkList.value = (res.data?.list || []).map((item) => ({
      ...item,
      month: parseTimeMonth(item.month, "{y}-{m}"),
      ratio: item.ztValue ? (item.checkValue / item.ztValue).toFixed(4) : "",
    }));
    checkTotal.value = res.data?.total || 0;
  });
}
const checkDialogVisible = ref(false);
const checkForm = reactive({ zt: "", month: "", ztValue: "", checkValue: "", ratio: "" });
const checkRules = {
  zt: [{ required: true, message: "请选择载体", trigger: "change" }],
  month: [{ required: true, message: "请选择年月", trigger: "change" }],
  ztValue: [{ required: true, message: "请获取载体电量", trigger: "change" }],
  checkValue: [{ required: true, message: "请输入容量电量", trigger: "blur" }],
  ratio: [{ required: true, message: "请输入系数", trigger: "change" }],
};
const checkFormRef = ref();
function openCheckDialog() {
  checkForm.zt = feeDialogRow.nr || "";
  checkForm.month = getLastMonthStr();
  checkForm.ztValue = "";
  checkForm.checkValue = "";
  checkForm.ratio = "";
  checkDialogVisible.value = true;
  fetchZtValue();
}
function fetchZtValue() {
  if (checkForm.zt && checkForm.month) {
    getCarrierEnergy({ zt: checkForm.zt, month: checkForm.month }).then((res) => {
      checkForm.ztValue = res.data || "";
      calcCheckRatio();
    });
  } else {
    checkForm.ztValue = "";
    checkForm.ratio = "";
  }
}
function calcCheckRatio() {
  const ztValue = parseFloat(checkForm.ztValue);
  const checkValue = parseFloat(checkForm.checkValue);
  checkForm.ratio = ztValue && checkValue ? (checkValue / ztValue).toFixed(4) : "";
}
function submitCheckForm() {
  checkFormRef.value.validate((valid) => {
    if (!valid) return;
    addCheckEnergy({ ...checkForm, zt: checkForm.zt }).then((res) => {
      if (res.code === 200) {
        checkDialogVisible.value = false;
        checkQuery.pageNum = 1;
        getCheckList();
      }
    });
  });
} 

// 电表费用相关
const meterFeeList = ref([]);
const meterFeeLoading = ref(false);
const meterFeePage = reactive({ pageNum: 1, pageSize: 10, total: 0 });
// 电表费用分页查询
function getMeterFeeList() {
  meterFeeLoading.value = true;
  if (meterFeeConfirmed.value) {
    confirmMeterFee({
      date: getLastMonthStr(),
      zt: feeDialogRow.nr,
      dflx: feeDialogRow.dflx,
      pageNum: meterFeePage.pageNum,
      pageSize: meterFeePage.pageSize,
    }).then((res) => {
      meterFeeList.value = res.data?.list || [];
      meterFeePage.total = res.data?.total || 0;
      meterFeeLoading.value = false;
    }).catch(() => {
      meterFeeLoading.value = false;
    });
  } else {
    selectMeterFeeList({
      zt: feeDialogRow.nr,
      month: getLastMonthStr(),
      dflx: feeDialogRow.dflx,
      pageNum: meterFeePage.pageNum,
      pageSize: meterFeePage.pageSize,
    }).then((res) => {
      meterFeeList.value = res.data?.list || [];
      meterFeePage.total = res.data?.total || 0;
      meterFeeLoading.value = false;
    }).catch(() => {
      meterFeeList.value = [];
      meterFeePage.total = 0;
      meterFeeLoading.value = false;
    });
  }
}

// 客户电费相关
const zhFeeList = ref([]);
const zhFeeLoading = ref(false);
const zhFeePage = reactive({ pageNum: 1, pageSize: 10, total: 0 });
function getZhFeeList() {
  zhFeeLoading.value = true;
  selectZhFeeList({
    zt: feeDialogRow.nr,
    month: getLastMonthStr(),
    dflx: feeDialogRow.dflx,
    pageNum: zhFeePage.pageNum,
    pageSize: zhFeePage.pageSize,
  })
    .then((res) => {
      zhFeeList.value = res.data?.list || [];
      zhFeePage.total = res.data?.total || 0;
      zhFeeLoading.value = false;
    })
    .catch(() => {
      zhFeeList.value = [];
      zhFeePage.total = 0;
      zhFeeLoading.value = false;
    });
}

// 确认电表费用
function handleConfirmMeterFee() {
  confirmMeterFee({
    date: getLastMonthStr(),
    zt: feeDialogRow.nr,
    dflx: feeDialogRow.dflx,
    pageNum: meterFeePage.pageNum,
    pageSize: meterFeePage.pageSize,
  }).then((res) => {
    if (res.code === 200) {
      meterFeeList.value = res.data?.list || [];
      meterFeePage.total = res.data?.total || 0;
      meterFeeConfirmed.value = true;
    }
    meterFeeLoading.value = false;
  }).catch(() => {
    meterFeeLoading.value = false;
  
  });
}
// 确认客户电费
function handleConfirmZhFee() {
  confirmZhFee({
    date: getLastMonthStr(),
    zt: feeDialogRow.nr,
    dflx: feeDialogRow.dflx,
  }).then((res) => {
    if (res.code === 200) {
               proxy.$modal.msgSuccess(res.msg || "客户电费确认成功");

           router.back();

    }
  });
}

// 步骤条操作
function feePrevStep() {
    if (showMeterFeeStep.value&& meterFeeConfirmed.value) {
    handleConfirmMeterFee();
    meterFeeConfirmed.value = false; // 标记电表费用已确认
  }
  if (feeStep.value > 0) feeStep.value--;
}
const meterFeeConfirmed = ref(false); // 电表费用确认状态
function feeNextStep() {
    console.log("当前步骤:", feeStep.value, "最大步骤:", feeMaxStep.value, "是否显示电表费用步骤:", showMeterFeeStep.value, "电表费用已确认:", meterFeeConfirmed.value);
   if (showMeterFeeStep.value&& !meterFeeConfirmed.value) {
    handleConfirmMeterFee();
    meterFeeConfirmed.value = true; // 标记电表费用已确认
  }else if (feeStep.value === feeMaxStep.value) {
    handleConfirmZhFee() 
  } else if (feeStep.value < feeMaxStep.value) {
    feeStep.value++;
  }
}


function parseTimeMonth(time, fmt = "{y}-{m}") {
  if (!time) return "";
  const date = typeof time === "string" ? new Date(time) : time;
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  return fmt.replace("{y}", y).replace("{m}", m);
}

// 步骤切换时自动加载数据
watch(feeStep, (val) => {
  if (val === 1 && feeDialogRow.dflx == 2) {
    checkQuery.zt = feeDialogRow.nr;
    checkQuery.month = getLastMonthStr();
    checkQuery.pageNum = 1;
    getCheckList();
  }
   
  if (showMeterFeeStep.value) {
    meterFeePage.pageNum = 1;
    getMeterFeeList();
  }
  if (val === feeMaxStep.value) {
    zhFeePage.pageNum = 1;
    getZhFeeList();
  }
});
onMounted(() => {
  loadMeterList();
//   getCheckList(); 
  // 可选：fetchCarrierList();
});
</script>

<style scoped>
/* 可根据需要自定义样式 */
</style>